package com.rop.system.filter;

import com.alibaba.fastjson.JSON;
import com.rop.result.Result;
import com.rop.result.ResultCodeEnum;
import com.rop.util.JwtHelper;
import com.rop.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @Title: TokenAuthenticationFilter
 * @Author Rop
 * @Date 2023/5/13 17:12
 * @description: 认证解析token过滤器
 */

public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private static final String path = "/admin/system/index/login";

    private RedisTemplate redisTemplate;

    public TokenAuthenticationFilter(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        logger.info("uri:" + request.getRequestURI());

        // 如果是登录接口，直接放行
        if (Objects.equals(path, request.getRequestURI())) {
            filterChain.doFilter(request,response);
            return;
        }

        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        if (Objects.nonNull(authentication)) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(request, response);
        } else {
            ResponseUtil.out(response, Result.build(null, ResultCodeEnum.PERMISSION));
        }
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // token至于header里
        String token = request.getHeader("token");
        logger.info("token:" + token);

        if (StringUtils.isNotBlank(token)) {
            String username = JwtHelper.getUsername(token);
            logger.info("username:" + username);

            if (StringUtils.isNotBlank(username)) {
                String authoritiesString = (String) redisTemplate.opsForValue().get(username);
                List<Map> mapList = JSON.parseArray(authoritiesString, Map.class);
                List<SimpleGrantedAuthority> authorities = new ArrayList<>();

                for (Map map : mapList) {
                    authorities.add(new SimpleGrantedAuthority((String) map.get("authority")));
                }

                return new UsernamePasswordAuthenticationToken(username, null, authorities);
            }
        }

        return null;
    }
}
